<template>
  <Screen v-if="screening" />
  <Editor v-else-if="_isPC" />
  <Mobile v-else />

  <FullscreenSpin :loading="isRefresh" :tip="tipTxt" />
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { storeToRefs } from 'pinia'
import { getHashData } from '@/utils/getHashData'
import { deleteDiscardedDB } from '@/utils/database'
import { useScreenStore, useMainStore, useSnapshotStore, usePageParamsStore } from '@/store'
import { LOCALSTORAGE_KEY_DISCARDED_DB } from '@/configs/storage'
import usePPTTemplate from '@/hooks/usePPTTemplate'

import { isPC } from './utils/common'

import Editor from './views/Editor/index.vue'
import Screen from './views/Screen/index.vue'
import Mobile from './views/Mobile/index.vue'
import FullscreenSpin from '@/components/FullscreenSpin.vue'

const _isPC = isPC()

const mainStore = useMainStore()
const snapshotStore = useSnapshotStore()
const { databaseId } = storeToRefs(mainStore)
const { screening } = storeToRefs(useScreenStore())
const pageParams = usePageParamsStore()

if (import.meta.env.MODE !== 'development') {
  window.onbeforeunload = () => false
}

const pptTemplate = usePPTTemplate()
const tipTxt = ref<string>('')
const isRefresh = ref(false)

/**
 * 获取路由中的参数
 */
setPageParams()
async function setPageParams() {
  console.log('hashChange')
  const data = getHashData()
  if (data.id) {
    pageParams.setAllParams(data)

    tipTxt.value = 'PPT加载中...'
    isRefresh.value = true
    await pptTemplate.getResourceware()
    tipTxt.value = ''
    isRefresh.value = false

  }
}

window.addEventListener('hashchange', setPageParams)

onMounted(async () => {
  await deleteDiscardedDB()
  snapshotStore.initSnapshotDatabase()
  mainStore.setAvailableFonts()

  // 向父项目发送消息
  if (window.parent) {
    window.parent.postMessage({
      version: '1.0.1',
      templateList: pptTemplate.templateList
    }, '*')
  }
})

// 应用注销时向 localStorage 中记录下本次 indexedDB 的数据库ID，用于之后清除数据库
window.addEventListener('unload', () => {
  const discardedDB = localStorage.getItem(LOCALSTORAGE_KEY_DISCARDED_DB)
  const discardedDBList: string[] = discardedDB ? JSON.parse(discardedDB) : []

  discardedDBList.push(databaseId.value)

  const newDiscardedDB = JSON.stringify(discardedDBList)
  localStorage.setItem(LOCALSTORAGE_KEY_DISCARDED_DB, newDiscardedDB)
})
</script>

<style lang="scss">
#app {
  height: 100%;
}
</style>